#-----------------------------------------------
# 源文件路径，使用相对路径
#-----------------------------------------------
# src := $(foreach d, $(srcdir), $(wildcard $(d)/*.c))
src := mod.c

#-----------------------------------------------
# 获取当前路径和顶层目录的相对路径名称
#-----------------------------------------------
ROOT_DIR ?= .
OBJS_CACHE ?= objs.cache
BUILD_DIR ?= .
dirname := $(shell realpath --relative-to $(ROOT_DIR) .)
curdir := $(shell pwd)

#-----------------------------------------------
# 头文件路径，使用绝对路径
#-----------------------------------------------
INCLUDE := -I$(INCLUDE_ENV) \
-I$(curdir)

#-----------------------------------------------
# 编译参数
#-----------------------------------------------
CFLAGS := $(CFLAGS_ENV)

#-----------------------------------------------
# 添加子模块，使用相对路径
#-----------------------------------------------
MOD := 

#-----------------------------------------------
# 编译前准备，获取当前路径名称和顶层目录的相对路径
#-----------------------------------------------
obj := $(src:.c=.o)
dep := $(src:.c=.d)
build := $(BUILD_DIR)/$(dirname)
objs := $(addprefix $(build)/, $(obj))
deps := $(addprefix $(build)/, $(dep))
$(shell echo $(objs) >> $(OBJS_CACHE))

all: module $(objs)

#-----------------------------------------------
# 子模块编译
#-----------------------------------------------
module: ${MOD}

${MOD}:
	@echo 
	@+${MAKE} -C $@
	@echo 

-include $(deps)

#-----------------------------------------------
# 生成.o文件的所有依赖关系
#-----------------------------------------------
$(build)/%.o: %.c
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) $(INCLUDE) -c $(curdir)/$< -o $@ 

#-----------------------------------------------
# 生成.d文件的所有依赖关系
#-----------------------------------------------
$(build)/%.d: %.c
	@set -e; mkdir -p $(@D); rm -f $@; \
	$(CC) -MM $(CFLAGS) $(INCLUDE) $< > $@.$$$$; \
	sed 's,\($(*F)\)\.o[ :]*,$(build)/$(<D)/\1.o $@ : ,g' < $@.$$$$ > $@; \
	rm -f $@.$$$$;\

#echo "generate dependencies $(@F) ."

.PHONY: clean clean_all $(MOD)

#-----------------------------------------------
# 子模块clean
#-----------------------------------------------
MOD_CLEAN = $(addprefix clean_, ${MOD})
$(MOD_CLEAN):
	@echo 
	@+${MAKE} -C $(patsubst clean_%,%,$@) clean
	@echo 

MOD_CLEAN_ALL = $(addprefix clean_all_, ${MOD})
$(MOD_CLEAN_ALL):
	@echo 
	@+${MAKE} -C $(patsubst clean_all_%,%,$@) clean_all
	@echo 

clean: $(MOD_CLEAN)
	@echo "Cleanning ..."
	-@rm -f $(objs)
	@echo "Clean completed."

clean_all: $(MOD_CLEAN_ALL)
	-@rm -f $(deps) $(objs) $(OBJS_CACHE)
	@echo "Clean all."
